<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);

class manage extends admin
{

    private $db,$tsmodel,$talent_pic_model;

    public $siteid;

    public $agency_branch;

    public $agency_type;

    function __construct()
    {
        parent::__construct();
        pc_base::load_app_func('global');
        $this->db = pc_base::load_model('subject_live_model'); // 加载subject_live_model
        $this->dynamics_db = pc_base::load_model('subject_dynamics_model'); // 加载直播动态关联model
        $this->suser_db = pc_base::load_model('subject_user_model'); // 加载直播用户关联model
        $this->dynamic_db = pc_base::load_model('subject_dynamic_model');//加载动态model
        $this->tsmodel = pc_base::load_model('pass_talent_model');
        $this->talent_pic_model = pc_base::load_model('pass_talent_pic_model');
        $this->siteid = get_siteid(); // 获取当前站点ID
        $model_setting=pc_base::load_model('site_setting_model');//加载设置类model
        $this->t_type = $model_setting->getValue("talent_type",$this->siteid);//获取人才类型
        $this->admin_username = param::get_cookie('admin_username'); // 获取当前登录的管理员
    }

    /**
     * 直播列表
     * 
     */
    public function init()
    {
        $show_dialog = $show_validator = true;
        $show_header = '';
        $where .= " status != 4";
        //搜索框
        $name = empty($_GET['name']) ?'':$_GET['name'] ;#直播名称
        if(!empty($name)){
            $where .= ' and title like "%'.$name.'%"';
        }

        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;#获取页码
        //查询直播信息
        $gameinfo = $this->db->select($where,"*","", 'id DESC , sort DESC');#根据 update_time 降序排列
        $gameinfo=getTreeList($gameinfo,0);
        //获取管理员信息
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $administrators = $admin_model->getRealnameInfo();
        //数据重构：加上最后编辑者信息
        foreach ($gameinfo as $key=>$value){
            foreach ($administrators as $key2=>$value2){
                if($value['updated_by'] == $key2){
                    $value['publisher'] = $value2;
                    $gameinfo[$key] = $value;
                    break;
                }
            }
        }
       $pages = $this->db->pages;
        include $this->admin_tpl('subject_live_list');
    }

    /**
     * 直播添加
     */
    public function add()
    {
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['sort']   =  0;#sort排序字段初始值给1
            $data['created_by']  =  $_SESSION['userid'];#管理用户ID
            $data['updated_by']  =  $_SESSION['userid'];#管理用户ID
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $result = $this->db->insert($data,true);
            if ($result) {
                $id = $this->db->insert_id();
            	//记录行为日志
            	$log_content = '<span style="color:green;">添加直播</span>[直播id：'.$id.'；直播名称：'.$data['title'].']';
            	$this->manage_admin_log($log_content);
                $url='?m=subject_live&c=manage&a=init';
                showmessage(L('add_success'), $url);
            } else {
                showmessage(L('add_error'), HTTP_REFERER);
            }
        } else {
            $show_dialog = $show_validator = true;
            $show_header = '';
            $id = isset($_GET['id']) ? $_GET['id'] :0;

            //$show_dialog = $show_validator = true;
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);
            include $this->admin_tpl('subject_live_add');
        }
    }

    /**
     *直播编辑
     */
    public function edit()
    {
        //如果没获取到id，则视为非法请求
        $id = isset($_GET['id']) ? $_GET['id'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
        $upinfo = $_POST['data'];
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
//             echo "<pre>";print_r($data);die;
            $data['updated_by'] =  $_SESSION['userid'];
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $result = $this->db->update($data, array(
                'id' => $id
            ));
            if ($result) {
            	//记录行为日志
            	$log_content = '<span style="color:blue;">修改直播</span>[直播id：'.$id.'；直播名称：'.$data['title'].']';
            	$this->manage_admin_log($log_content);
                $url='?m=subject_live&c=manage&a=init';
                showmessage(L('edit_success'), $url);
            } else {
                showmessage(L('edit_error'), HTTP_REFERER);
            }
        } else {
            $data = $this->db->get_one(array(
                'id' => $id
            ));
            $show_dialog = $show_validator = true;
            $show_header = '';
            include $this->admin_tpl('subject_live_edit');
        }
    }

    /**
     * 删除、批量删除直播
     */
    public function del()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $name = $_REQUEST['name']?$_REQUEST['name']:'请联系管理员！';
        if (is_array($id)) {
            foreach ($id as $k => $v) {

                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }
        //直播软删除
        $result = $this->db->update(array(
            'status' => '4'#状态：1准备中,2启用,3关闭,4删除
        ), "id in ('$id')");
        
        if ($result) {
        	//记录行为日志
        	$del_id = explode('\',\'', $id);
        	$new_id = implode(',', $del_id);
        	$log_content = '<span style="color:red;">删除直播</span>[直播id：'.$new_id.'；直播名称：'.$name.']';
        	$this->manage_admin_log($log_content);
            showmessage(L('del_success'), HTTP_REFERER);
        } else {
            showmessage(L('del_error'), HTTP_REFERER);
        }
    }

    /*
     * 直播详情
     */
    public function view()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $data = $this->db->get_one(array(
            'id' => $id
        ));
        $show_header = '';
        include $this->admin_tpl('subject_live_view');
    }

    /*
     * 直播关联人才-列表
     */
    public function pass_talent()
    {
        $pass_talent_model=pc_base::load_model('pass_talent_model');
        $pass_talent_pic_model=pc_base::load_model('pass_talent_pic_model');
        
        $types = $this->t_type;
        
        $sql="select n.*,t.id as cid,t.tid,t.pid,t.image_vertical as image_shuxing from nsrweb_pass_talent as t LEFT JOIN nsrweb_talent as n on t.tid =n.id where n.status=1 ";
        $sql .= "  and n.siteid =" . $this->siteid;
        if (isset($_GET['user_name']) && !empty($_GET['user_name'])) {
            $name = trim($_GET['user_name']);
            $sql .= " and `real_name` like '%$name%' ";
        }
        $column_name = trim($_GET['name']);
        if (isset($_GET['talent_type']) && !empty($_GET['talent_type'])) {
            switch ($_GET['talent_type']) {
                case '1':
                    $sql .= " and n.is_student = 1";
                    break;
                case '2':
                    $sql .= " and n.is_signed_model = 1";
                    break;
                case '3':
                    $sql .= " and n.is_hot = 1";
                    break;
                case '4':
                    $sql .= " and n.is_judge = 1";
                    break;
                case '5':
                    $sql .= " and n.is_guest = 1";
                    break;
                case '6':
                    $sql .= " and n.is_star = 1";
                    break;
                case '7':
                    $sql .= " and n.is_mentor = 1";
                    break;
                case '8':
                    $sql .= " and n.is_moter = 1";
                    break;
                default:
                    break;
            }
        }
        
        $sql .= " order by t.id desc,t.tid desc,n.id DESC ";
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $talentinfo = $this->db->my_listinfo($sql, $page, 10);
        
        $pages = $this->db->pages;
        $show_header = '';
        include $this->admin_tpl('pass_talent_list');
    }

    /**
     * 排序
     */
    public function listorder() {
        if(isset($_GET['dosubmit'])) {
            foreach($_POST['sort'] as $id => $listorder) {
                $this->db->edit(array('sort'=>$listorder),$id);
                //添加缓存
                //$this->db->redisCache($id);
            }
        	//记录行为日志
        	$log_content = '<span style="color:orange;">直播排序</span>';
        	$this->manage_admin_log($log_content);
            showmessage(L('operation_success'));
        } else {
            showmessage(L('operation_failure'));
        }
    }

    /**
     * 用户游戏结果管理
     */
    public function user_game_list ()
    {
        $subject_live_result = pc_base::load_model('subject_live_result_model');
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $where = " id > 0 ";
        $passGameList = $this->db->getGameList();
        if(isset($_GET['user_name']) && $_GET['user_name']) {
            $user_name = trim($_GET['user_name']);
            $where .= " and `user_name` like '%$user_name%' ";
        }
        if(isset($_GET['is_success']) && $_GET['is_success']) {
            $is_success = intval($_GET['is_success']);
            if ($is_success == 1) {
               $where .= " and is_success = " . $is_success; 
            } else {
               $where .= " and is_success = 0 "; 
            }
        }
        if(isset($_GET['platform']) && $_GET['platform']) {
            $platform = intval($_GET['platform']);
            $where .= " and platform = " . $platform;
        }
        if(isset($_GET['subject_live_id']) && $_GET['subject_live_id']) {
            $subject_live_id = intval($_GET['subject_live_id']);
            $where .= " and subject_live_id = " . $subject_live_id;
        }
        $lists = $subject_live_result->listinfo($where,'id DESC',$page,10);
        foreach ($lists as $k => $v) {
            $info = $this->db->get_one(array('id'=>$v['subject_live_id']));
            $lists[$k]['pass_name'] = $info['name'];
            $pass_talent_pic_ids = explode(',',$v['pass_talent_pic_ids']);
            if (empty($pass_talent_pic_ids)) {
                $lists[$k]['pass_pic'] = '';
            } else {
                $infoPic = $this->talent_pic_model->get_one(array('id'=>$pass_talent_pic_ids[0]));
                $lists[$k]['pass_pic'] = $infoPic['pic_url'];
            }
        }
        $pages = $subject_live_result->pages;
        include $this->admin_tpl('user_game_list');
    }
    
    /**
     * 直播关联动态列表
     */
    public function dynamics_list() {
    	$id = $_GET['id'];
    	$page = $_GET['page'] ? intval($_GET['page']) : 1;	
    	$sql = "";
    	//搜索框
    	$name = empty($_GET['name']) ? '':$_GET['name'] ;#用户名
    	if(!empty($name)){
    		$sql .= "select a.*,a.id as aid,b.* from nsrweb_subject_live_dynamic_rel as a left join nsrweb_talent_dynamic as b on a.talent_dynamic_id = b.id where a.subject_live_id = ".$id." and b.user_name like '%$name%' order by b.id DESC";
    	} else {
    		$sql .= "select a.*,a.id as aid,b.* from nsrweb_subject_live_dynamic_rel as a left join nsrweb_talent_dynamic as b on a.talent_dynamic_id = b.id where a.subject_live_id = ".$id." order by b.id DESC";
    	}
    	$info = $this->dynamics_db->my_listinfo($sql,$page,10);
    	$pages = $this->dynamics_db->pages;
    	$liveinfo = $this->db->get_one(array('id'=>$id));
    	$show_header = false;
    	include $this->admin_tpl('subject_dynamics_list');
    }
    
    /**
     * 直播动态删除
     */
    public function dynamics_del(){
    	$id = $_REQUEST['did'];//动态ID
    	$subject_id = $_REQUEST['sid'];//直播ID
    	if (!isset($id) || empty($id)) {
    		showmessage(L('message_not_exits'),HTTP_REFERER);
    	}
    	if (is_array($id)) {
    		foreach ($id as $k=>$v){
    			if (intval($v)) {
    				$id[$k] = intval($v);
    			} else {
    				unset($id[$k]);
    			}
    		}
    		$id = implode('\',\'', $id);
    	}
    	$del_did = str_replace("'", "", $id);
    	$result = $this->dynamic_db->update(array('status'=>2),"id in ('$id')");
    	if ($result) {
    		//记录行为日志
    		$log_content = '<span style="color:red;">删除直播关联动态</span>[动态id：'.$del_did.']';
    		$this->manage_admin_log($log_content);
    		showmessage(L('del_success'),'?m=subject_live&c=manage&a=dynamics_list&id='.$subject_id);
    	} else {
    		showmessage(L('del_error'),HTTP_REFERER);
    	}
    }
    
    /**
     * 直播关联用户列表
     */
    public function user_list(){
    	$subject_id = $_GET['id'];
    	$page = $_GET['page'] ? intval($_GET['page']) : 1;
    	$sql = "";
    	$sql .= "select s.*,s.id as sid,s.create_time as screate_time,u.* from nsrweb_subject_live_user_rel as s left join nsrweb_user_info as u on s.user_id = u.id where s.subject_live_id = ".$subject_id;
    	//搜索框
    	$nickname = empty($_GET['nickname']) ? '':$_GET['nickname'] ;#用户昵称
    	$tel = empty($_GET['tel']) ? '' : $_GET['tel'];#用户联系方式
    	if (!empty($nickname)) {
    		$sql .= " and u.nickname like '%$nickname%'";
    	}
    	if(!empty($tel)){
    		$sql .= " and u.tel=".$tel;
    	}
    	$sql .= " order by s.id DESC";
    	$info = $this->suser_db->my_listinfo($sql,$page,10);
    	$pages = $this->suser_db->pages;
    	$liveinfo = $this->db->get_one(array('id'=>$subject_id));
    	//获取用户管理员真实姓名数据
    	$admin_model = pc_base::load_model('admin_model');
    	$adminInfo = $admin_model->getRealnameInfo();
    	$show_header = false;
    	include $this->admin_tpl('subject_user_list');
    }
}